#!/bin/bash

# create_users.sh
# 功能说明:
# 1. 支持通过命令行参数传入用户名和密码创建用户。
# 2. 支持通过文件传入用户列表（包括用户名和密码）批量创建用户。
# 3. 如果文件中用户未提供密码，自动生成随机密码并更新文件。
# 4. 所有需要管理员权限的操作通过 sudo 执行。

# 生成随机密码的函数
generate_random_password() {
  tr -dc 'A-Za-z0-9!@#$%^&*()_+~' </dev/urandom | head -c 12
}

# 创建用户的函数
create_user() {
  local username="$1"
  local password="$2"

  # 检查用户是否已存在
  if id "$username" &>/dev/null; then
    echo "User $username already exists. Skipping..."
  else
    # 创建用户并设置密码
    sudo useradd -m -s /bin/bash "$username"
    if [[ $? -eq 0 ]]; then
      echo "$password" | sudo passwd --stdin "$username" &>/dev/null
      if [[ $? -eq 0 ]]; then
        echo "User $username has been created successfully with the specified password."
      else
        echo "Failed to set the password for user $username."
      fi
    else
      echo "Failed to create user $username."
    fi
  fi
}

# 从文件处理用户的函数
process_file() {
  local file="$1"

  # 检查文件是否存在
  if [[ ! -f "$file" ]]; then
    echo "File $file does not exist. Please provide a valid file."
    exit 1
  fi

  # 临时文件用于更新密码
  local temp_file="$(mktemp)"

  # 逐行读取文件内容并创建用户
  while IFS= read -r line; do
    # 跳过空行和注释行
    [[ -z "$line" || "$line" == \#* ]] && continue

    # 提取用户名和密码
    local username password
    username=$(echo "$line" | awk '{print $1}')
    password=$(echo "$line" | awk '{print $2}')

    # 如果密码为空，生成随机密码
    if [[ -z "$password" ]]; then
      password=$(generate_random_password)
      echo "Generated random password for user $username: $password"
    fi

    # 创建用户
    create_user "$username" "$password"

    # 将用户名和密码写回临时文件
    echo "$username $password" >> "$temp_file"
  done < "$file"

  # 覆盖原始文件，更新密码信息
  sudo mv "$temp_file" "$file"
  echo "Password file $file has been updated with any missing passwords."
}

# 主函数
main() {
  if [[ $# -eq 0 ]]; then
    echo "Usage: $0 [-f user_file] [username password]"
    exit 1
  fi

  # 处理命令行参数
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -f|--file)
        shift
        if [[ -n "$1" ]]; then
          process_file "$1"
          shift
        else
          echo "Error: Missing file name after -f."
          exit 1
        fi
        ;;
      *)
        if [[ $# -ge 2 ]]; then
          local username="$1"
          local password="$2"
          create_user "$username" "$password"
          shift 2
        else
          echo "Error: Missing username or password."
          exit 1
        fi
        ;;
    esac
  done
}

# 执行主函数
main "$@"

